import request from '@/utils/request'
import { RootThunkAction } from '..'
import { ArticleAction, Comment } from '../reducers/article'

export function getArticleDetail(id: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get('/articles/' + id)
    dispatch({
      type: 'article/saveDetail',
      payload: res.data,
    })
  }
}

// 获取文章的评论数据
export function getCommentList(id: string): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get('/comments', {
      params: {
        type: 'a',
        source: id,
      },
    })

    dispatch({
      type: 'article/saveComment',
      payload: res.data,
    })
  }
}

export function getMoreCommentList(
  id: string,
  offset: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get('/comments', {
      params: {
        type: 'a',
        source: id,
        offset,
      },
    })

    dispatch({
      type: 'article/saveMoreComment',
      payload: res.data,
    })
  }
}

// 点赞
export function likeArticle(id: string, attitude: number): RootThunkAction {
  return async (dispatch) => {
    if (attitude === 1) {
      // 取消点赞
      await request.delete('/article/likings/' + id)
    } else {
      // 点赞
      await request.post('/article/likings', { target: id })
    }

    // 刷新
    await dispatch(getArticleDetail(id))
  }
}

// 点击收藏
export function collectArticle(
  id: string,
  is_collected: boolean
): RootThunkAction {
  return async (dispatch) => {
    if (is_collected) {
      // 取消收藏
      await request.delete('/article/collections/' + id)
    } else {
      await request.post('/article/collections', { target: id })
    }
    // 刷新
    await dispatch(getArticleDetail(id))
  }
}

// 文章详情页关注
// export function followAuth(
//   userId: string,
//   is_follow: boolean
// ): RootThunkAction {
//   return async (dispatch, getState) => {
//     if (is_follow) {
//       await request.delete('/user/followings/' + userId)
//     } else {
//       await request.post('/user/followings', {
//         target: userId,
//       })
//     }
//     await dispatch(getArticleDetail(getState().article.detail.art_id))
//   }
// }

// 添加评论
export function addComment(
  articleId: string,
  content: string
): RootThunkAction {
  return async (dispatch, getState) => {
    const res = await request.post('/comments', {
      target: articleId,
      content,
    })
    // console.log(res)
    dispatch({
      type: 'article/saveNewComment',
      payload: res.data.new_obj,
    })
    dispatch(getArticleDetail(getState().article.detail.art_id))
  }
}

// 更新文章评论数
export function updateComment(comment: Comment): ArticleAction {
  return {
    type: 'article/updateComment',
    payload: comment,
  }
}
